import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import axios from '@/plugins/axios'
import utils from '@/plugins/utils'
import mainRoutes from './modules/index'
import findPwd from './modules/findpwd'

Vue.use(Router)

// 开发环境和生产环境使用不同的加载方式
const _import =
  process.env.NODE_ENV === 'production'
    ? file => () => import('@/views/' + file + '.vue')
    : file => require('@/views/' + file + '.vue').default

//  meta中自定义属性功能
//  title: 页面标题 | String
//  permission: 进入页面所需权限 | String
//  noLogin: 进入该页面无需登录 | Boolean
//  multipage: 指示一个路由参数，是否新增页签

const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  scrollBehavior: () => ({ y: 0 }),
  routes: [
    {
      path: '/login',
      component: _import('common/login'),
      name: 'login',
      meta: { title: '登录', noLogin: true }
    },
    {
      path: '/',
      component: _import('main/main'),
      name: 'main',
      redirect: { name: 'index' },
      meta: { title: '布局框架' },
      children: [...mainRoutes]
    },
    {
      path: '*',
      redirect: { name: '404' }
    },
    ...findPwd
  ]
})

router.beforeEach((to, from, next) => {
  if (to.meta.noLogin) {
    next()
  } else {
    if (to.meta.title) document.title = to.meta.title + '---云签'
    let token = window.localStorage.getItem('token')
    if (!token || !/\S/.test(token)) {
      utils.clearLoginInfo()
      utils.sysOut(to)
    } else {
      if (!store.state.user.init) {
        initUser(to, from, next)
      } else {
        vaildUser(to, from, next)
      }
    }
  }
})

const initUser = (to, from, next) => {
  let num = 0
  axios({
    url: axios.setUrl('auth/currentPrimes'),
    method: 'get',
    params: axios.setParams()
  })
    .then(({ data }) => {
      if (data && data.code === '0') {
        store.commit('user/updateInit', true)
        store.commit('user/updateInitText', '')
        store.commit('user/updateId', data.data.userId)
        store.commit('user/updateName', data.data.loginUname)
        store.commit(
          'common/updateMenuList',
          utils.arrayToTree(data.data.sysMenus, {
            id: 'menuId',
            pid: 'parentMenuId',
            mainSort: 'treeLevel',
            minorSort: 'sortNo'
          })
        )
        store.commit(
          'common/updateMenuNameList',
          data.data.sysMenus.map(item => {
            return item.menuRouteName
          })
        )
        store.commit('user/updatePermList', data.data.primes)
        let userConfig = {}
        data.data.indvCfgs.forEach(item => {
          userConfig[item.indvCfgType] = isNaN(parseInt(item.indvCfgVal)) ? item.indvCfgVal : parseInt(item.indvCfgVal)
        })
        store.commit('user/updateHome', userConfig.LOGON_FIRSTPAGE || 'home')
        num += 1
        if (num === 2) {
          vaildUser(to, from, next)
        }
      } else {
        errorFun(data.data || data.msg || '用户信息获取失败，请稍后重试')
      }
    })
    .catch(() => {
      errorFun('获取用户信息请求发生了错误')
    })

  axios({
    url: axios.setUrl('sys/sysDict/all'),
    method: 'get',
    params: axios.setParams()
  })
    .then(({ data }) => {
      if (data && data.code === '0') {
        store.commit('user/updateDictList', data.data)
        store.commit('user/updateDictDbList', data.data)
        num += 1
        if (num === 2) {
          vaildUser(to, from, next)
        }
      } else {
        errorFun(data.data || data.msg || '字典信息获取失败')
      }
    })
    .catch(() => {
      errorFun('获取用户信息请求发生了错误')
    })

  let errorFun = msg => {
    utils.clearLoginInfo()
    utils.sysOut(to)
    store.commit('user/updateInitText', msg)
  }
}

const vaildUser = (to, from, next) => {
  if (to.meta.permission) {
    if (Vue.prototype.$auth(to.meta.permission)) {
      sendRecord(to)
      next()
    } else {
      next({ name: 'noPermission' })
    }
  } else {
    sendRecord(to)
    next()
  }
}

const sendRecord = to => {
  if (!to.meta.noRecord) Vue.prototype.$utils.sentRecord(to.path)
}

export default router
